package com.jing.myservice.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyComplexService extends Service {
    private static final String TAG = "MyComplexService";
    private final Messenger serviceMessenger = new Messenger(new IncomingHandler());
    private Messenger clientMessenger;
    private boolean isRunning = false;
    int count = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return serviceMessenger.getBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service created");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service destroyed");
        isRunning = false; // Ensure task stops
    }

    private void startBackgroundTask() {
        if (isRunning) return;
        isRunning = true;

        new Thread(() -> {
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    count++;
                    if (clientMessenger != null) {
                        Message msg = Message.obtain(null, 0);
                        Bundle bundle = new Bundle();
                        bundle.putInt("count", count);
                        msg.setData(bundle);
                        try {
                            clientMessenger.send(msg);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    startBackgroundTask();
                    break;
                case 2:
                    isRunning = false;
                    stopSelf();
                    break;
                case 3:
                    clientMessenger = new Messenger(msg.replyTo.getBinder());
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}
